#include <vector>
#include <iostream>
#include <map>

const std::vector<std::pair<int, int>> offset_coord = {{1, 2},
                                                       {1, -2},
                                                       {2, 1},
                                                       {2, -1},
                                                       {-1, 2},
                                                       {-1, -2},
                                                       {-2, 1},
                                                       {-2, -1}};
int m, n;
int dp[676][26][26];
void dfs(int id, int x, int y, int val, int k)
{
    if (k <= 0)
        return;
    if (dp[id][y][x] < val)
        return;
    dp[id][y][x] = val;

    for (int i = 0; i < offset_coord.size(); i++)
    {
        int nx = x + offset_coord[i].first;
        int ny = y + offset_coord[i].second;
        if (nx < 0 || nx >= n || ny < 0 || ny >= m)
        {
            continue;
        }

        dfs(id, nx, ny, val + 1, k - 1);
    }
}

int main()
{
    std::cin >> m >> n;

    std::map<std::pair<int, int>, int> coord_maps;
    int id = 0;
    for (int i = 0; i < m; i++)
    {
        std::string s;
        std::cin >> s;
        for (int j = 0; j < s.size(); j++)
        {
            if (s[j] != '.')
            {
                for (int i = 0; i < m; i++)
                {
                    for (int j = 0; j < s.size(); j++)
                    {
                        dp[id][i][j] = 1e9;
                    }
                }

                std::pair<int, int> key = {j, i};
                coord_maps[key] = s[j] - '0';
                dfs(id, j, i, 0, s[j] - '0');
                id++;
            }
        }
    }

    int res = 1e9;
    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            int id = 0;
            int minv = 0;
            for (auto it = coord_maps.begin(); it != coord_maps.end(); ++it)
            {
                minv += dp[id][i][j];
                id++;
            }
            res = std::min(res, minv);
        }
    }

    if (res > 1e9)
        std::cout << -1 << std::endl;
    else
        std::cout << res << std::endl;
    return 0;
}